import os
import re
import random
from datetime import datetime, time
from urllib.parse import urlparse

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


# 配置参数
BASE_PREFIX = "https:"  # URL前缀
MAX_RETRIES = 3         # 下载重试次数


def create_unique_folder():
    """创建唯一文件夹"""
    date_str = datetime.now().strftime("%Y%m%d")
    random_num = f"{random.randint(0, 9999):04d}"
    folder_name = f"onepiece_{date_str}_{random_num}"

    if not os.path.exists(folder_name):
        os.makedirs(folder_name)
    return folder_name


def download_image(url, save_folder):
    """下载单张图片"""
    try:
        # 提取文件名（去除查询参数）
        parsed = urlparse(url)
        filename = os.path.basename(parsed.path)
        if not filename:
            filename = f"unknown_{int(time.time())}.jpg"

        save_path = os.path.join(save_folder, filename)

        # 避免重复文件名
        counter = 1
        while os.path.exists(save_path):
            name, ext = os.path.splitext(filename)
            save_path = os.path.join(save_folder, f"{name}_{counter}{ext}")
            counter += 1

        # 配置会话
        session = requests.Session()
        session.mount('https://', requests.adapters.HTTPAdapter(max_retries=MAX_RETRIES))

        # 下载文件
        response = session.get(url,
                               stream=True,
                               timeout=10,
                               headers={'User-Agent': 'Mozilla/5.0'})
        response.raise_for_status()

        # 写入文件
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                if chunk:  # 过滤保持活动的数据块
                    f.write(chunk)
        return True, save_path

    except Exception as e:
        return False, str(e)

def get_img(url,download_folder):
    # 1. 初始化浏览器驱动（以Chrome为例）
    driver = webdriver.Chrome()  # 需提前安装对应版本驱动
    driver.get(url)  # 替换为目标页面URL

    # 2. 显式等待元素加载（关键步骤）
    try:
        # 根据ID定位元素的等待策略
        element = WebDriverWait(driver, 15).until(
            EC.presence_of_element_located(
                (By.ID, "shopify-section-template--15053875314736__main")  # 若ID固定则直接写死
            )
        )
    except:
        print("元素加载超时")
        driver.quit()
        exit()

    # print(element.get_attribute("outerHTML"))

    pattern = r'''
        src="(//mascaradelatex.com[^"]+)"  # 捕获src属性值
        (?:[^>]*?\bwidth=["']?600["']?)    # 非捕获组匹配width属性
        |
        src="(//mascaradelatex.com[^"]*?width=600[^"]*)"  # URL含width参数
    '''

    # 使用忽略空白和大小写模式
    matches = re.findall(pattern, element.get_attribute("outerHTML"), flags=re.IGNORECASE | re.VERBOSE)

    # 合并两个捕获组的结果
    urls = [m[0] or m[1] for m in matches if any(m)]

    print("匹配到的URL列表:")
    for url in urls:
        print(url)
        # 创建存储目录
    # 只下载第一张
    # 将集合转换为列表
    # urls_list = list(urls)
    # # 新建一个集合，只复制 urls 的第一个元素
    # new_set = {urls_list[0]}
    main_fuc(urls,download_folder)
    driver.quit()


def main_fuc(urls,download_folder):


    # 处理URL并下载
    success_count = 0
    for idx, url in enumerate(urls, 1):
        # 补全URL协议
        full_url = BASE_PREFIX + url if url.startswith("//") else url

        # 执行下载
        status, result = download_image(full_url, download_folder)

        # 输出结果
        if status:
            print(f"[{idx}/{len(urls)}] 下载成功：{result}")
            success_count += 1
        else:
            print(f"[{idx}/{len(urls)}] 下载失败：{result}")

    # 最终报告
    print(f"\n下载完成 | 成功：{success_count} | 失败：{len(urls) - success_count}")
    print(f"文件保存至：{os.path.abspath(download_folder)}")


if __name__ == '__main__':
    get_img("https://mascaradelatex.com/collections/one-piece/products/playera-para-hombre-nico-robin?variant=41605711134768")